import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/core/utils/log_util.dart';
import 'package:enterprise_v6_app/app/data/entities/application/basic_information/classes_config_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/task/scheduling_config_entity.dart';
import 'package:jiffy/jiffy.dart';

class SchedulingPlanController extends GetxController {
  /// 当前时间
  DateTime kToday = DateTime.now();

  /// 日历开始时间
  late DateTime kFirstDay;

  /// 日历结束时间
  late DateTime kLastDay;

  /// 班次列表
  List<ClassesConfigEntity> classesList = [];

  /// 班次对应的颜色
  Map<String, Color> colorMap = {};

  /// 当月班次和每日的对应关系
  Map<String, List<DateTime>> classedMap = {};

  @override
  void onInit() {
    super.onInit();
    kFirstDay = DateTime(kToday.year - 10);
    kLastDay = DateTime(kToday.year + 10);
    initData();
  }

  /// 初始化数据
  Future<void> initData() async {
    await getClassesConfigList();
    getMonthPlan();
  }

  /// 获取班次列表
  Future<void> getClassesConfigList() async {
    final res = await HttpUtil().generateGetRequest<List<ClassesConfigEntity>>(Interface.getClassesConfigList).execute();
    res.onSuccess((result) {
      if (result.data != null) {
        classesList = result.data!;
      }
      update();
    });
  }

  /// 获取颜色显示
  Color getColorFromHex(String hexColor) {
    if (hexColor.isEmpty) {
      return const Color(0xff918f8c);
    }
    hexColor = hexColor.replaceAll('#', '');
    if (hexColor.length == 6) {
      hexColor = 'FF$hexColor';
    }
    return Color(int.parse('0x$hexColor'));
  }

  /// 获取用户单月计划
  /// [focusedDay] 为空则查询当月
  Future<void> getMonthPlan({DateTime? focusedDay}) async {
    final DateTime monthStart = getFirstDayOfMonth(focusedDay ?? kToday); // 月开始时间
    final DateTime monthEnd = getLastDayOfMonth(focusedDay ?? kToday); // 月结束时间

    final response = await HttpUtil().generateGetRequest<List<SchedulingConfigEntity>>(Interface.getUserDutyList, queryParameters: {
      'startDate': Jiffy.parseFromDateTime(monthStart).format(pattern: 'yyyy-MM-dd HH:mm:ss'),
      'endDate': Jiffy.parseFromDateTime(monthEnd).format(pattern: 'yyyy-MM-dd HH:mm:ss'),
    }).execute();
    response.onSuccess((result) {
      if (result.data != null) {
        classedMap.clear();
        // 获取到当月排班数据
        final List<SchedulingConfigEntity> dataList = result.data!;
        // 循环设置班次
        for (var item in classesList) {
          final List<DateTime> timeList = [];
          for (var bean in dataList) {
            // 属于当前班次
            if (item.id == bean.classesId) {
              try {
                timeList.add(DateTime.parse(bean.onDutyDate));
              } catch (e) {
                AppLogger.printLog('时间转换异常$e');
              }
            }
          }
          classedMap[item.id] = timeList;
          colorMap[item.id] = getColorFromHex(item.classesColor);
        }
        update();
      }
    });
  }

  /// 获取当月开始时间
  DateTime getFirstDayOfMonth(DateTime dateTime) {
    return DateTime(dateTime.year, dateTime.month, 1);
  }

  /// 获取当月结束时间
  DateTime getLastDayOfMonth(DateTime dateTime) {
    final nextMonth = dateTime.month < 12 ? dateTime.month + 1 : 1;
    final year = nextMonth == 1 ? dateTime.year + 1 : dateTime.year;
    return DateTime(year, nextMonth, 1).subtract(const Duration(seconds: 1));
  }

  /// 判断当日是否存在该计划
  /// [classedId] 班次计划id
  /// [day] 当日时间
  bool isExistencePlan({required String classedId, required DateTime day}) {
    final timeList = classedMap[classedId];
    if (timeList == null) {
      return false;
    }
    for (var item in timeList) {
      // 是同一天
      if (item.year == day.year && item.month == day.month && item.day == day.day) {
        return true;
      }
    }
    return false;
    // return timeList.contains(day);
  }
}
